package com.kamistoat.netty.netty.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

/**
 * Netty 心跳检测服务端
 */
public class HeartServer {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    // 在BossGroup增加一个日志handler
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // netty提供库类IdleStateHandler, 执行空闲监测
                            // readerIdleTime: 表示多少时间没有读，就会触发读空闲事件
                            // writerIdleTime: 多少时间没有写，触发写空闲事件
                            // allIdleTime: 多少时间既没有读也没有写，触发读写空闲事件
                            pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));
                            // 对IdleStateHandler触发的空闲事件进行处理，IdleStateHandler规定，当自身触发空闲事件后，事件不会由自己处理，
                            // 而是会交给Pipeline中的下一个Handler处理，方式是调用下一个Handler的 userEventTriggered()方法
                            pipeline.addLast(new HeartServerHandler());
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(10001).sync();
            channelFuture.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
